/* User Login Screen/ Registration GUI
 * Team AutoLytics
 * Build one
 * 3 -15 -2011
 * 
 *
*/


import java.sql.*;
import java.awt.*;
import java.util.*;
import javax.swing.plaf.basic.*;
import javax.swing.border.*;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JLabel;
import javax.swing.JFrame;
import javax.swing.BoxLayout;
import javax.imageio.*;
import javax.swing.*;
import java.io.*;
import java.awt.event.*;
import javax.swing.JOptionPane;
import javax.mail.*;
import javax.mail.internet.*;

public class LoginScreen extends JFrame implements ActionListener{
  protected JButton submit;
  protected JButton register, submitCH;
  public Connection connect;
  protected Statement stmt;
  protected ResultSet rs;
  protected JPasswordField passfield;
  protected JTextField UIDfield, chField;
  protected JLabel UILabel, logoLabel, welcomeLabel;
  protected Image logo;
  protected JTextField first;
  protected JTextField last, EM;
  protected JButton forgot;
  protected JButton send;
  protected JTextField username, emailField;
  protected JPasswordField passenter;
  protected JComboBox type;
  protected JPanel content;
  protected JButton newuser;
  protected JFrame popUp, forgotWindow;
  protected String driver, maintenance, chOperator, chString="null";
   protected ClientModel client;
  public User currUser;
  
  
  public LoginScreen(Connection con, ClientModel clientelle){
    super(); //Make it a JFrame
    connect = con;
     client = clientelle;
    try{
      stmt = connect.createStatement();
    }catch(SQLException e1){
      System.out.println(e1);
    }
    
    content = (JPanel) getContentPane();
    content.setLayout(new GridBagLayout());
    
    UILabel = new JLabel("UserName: ");
    UIDfield = new JTextField(20);
    UIDfield.setVisible(true);
    
    JPanel passpane = new JPanel();
    passpane.setLayout(new GridBagLayout());
    GridBagConstraints c = new GridBagConstraints();
    
    JLabel passprompt = new JLabel("Password: ");
    
    passfield = new JPasswordField(20);

    passfield.setVisible(true);
    
    submit = new JButton("Submit");
    submit.addActionListener(this);
    
    register = new JButton("Register new User");
    register.addActionListener(this);
    
    forgot = new JButton("Forgot Username or Password?");
    forgot.addActionListener(this);
    
    JPanel north = new JPanel(new GridBagLayout());
    
    c.gridx=0;
    c.gridy=0;
    north.add(UILabel, c);
    c.gridx=1;
    north.add(UIDfield, c);

    c.gridy=1;
    c.gridx=0;
    north.add(passprompt, c);
    c.gridx=1;
    north.add(passfield, c);

    
    north.setOpaque(false);
    north.setVisible(true);

    
    File logoFile1 = new File("AutoBiography.png");
    try {
      logo = ImageIO.read(logoFile1);
    } catch (IOException e) {
      System.out.println("Image read error: "+e);
    }
    ImageIcon icon1 = new ImageIcon(logo.getScaledInstance(550, 60, 0));
    logoLabel = new JLabel();
    logoLabel.setIcon(icon1);

    c.anchor = GridBagConstraints.PAGE_START;
    c.gridx=0;
    c.gridy=0;
    content.add(logoLabel, c);
    
    welcomeLabel = new JLabel("Welcome to AutoBiography! If you already have a username and password, please enter them.\n If not, please click \"Register new User\" to create a User profile.");
    
    c.gridy =1;
    c.ipady = 100;
    content.add(welcomeLabel, c);
    
    c.anchor = GridBagConstraints.CENTER;
    c.gridx =0;
    c.gridy=2;
    c.ipady = 200;
    content.add(north, c);
    
    c.gridy=3;
    c.ipady = 0;
    content.add(submit, c);

    c.gridy=4;
    content.add(register, c);

    c.gridy = 5;
    content.add(forgot, c);
    
    
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    content.setBackground(Color.white);
    content.setVisible(true);   
    setContentPane(content);
    pack();
    
    setSize(1200, 800);
    setVisible(true);
    
  }
  
  public void actionPerformed(ActionEvent evt){
    
    if (evt.getSource() == submit){
      String UID = UIDfield.getText();
      String pass = new String(passfield.getPassword());
      SecureLogin safe = new SecureLogin();
        // Set the user to the current login info.
       //User test = new User("", "", UID, pass user,
       try{
        if (safe.authenticate(connect, UID, pass)){
            rs = stmt.executeQuery("SELECT * FROM USERS WHERE UID = '"+UID+"'");
            //choice = 4
            currUser = returnUser(rs);
            AutoBiography.addUser(currUser);
            AutoBiography.setUser(currUser);
            setVisible(false);
            new CarSelector(currUser, connect);
        }
        else{
          JOptionPane.showMessageDialog(this, "That is not correct login info. Create an account by registering.");
        }
      }
      catch(Exception e){
        System.out.println(e);
      }
    }
    else if(evt.getSource() == register){
      //Create register popup window ********
        
      popUp = new JFrame("Register New User");
      
      JLabel firstL = new JLabel("First Name: ");
      first = new JTextField(20);
      first.setPreferredSize(new Dimension(300, 20));

      JLabel lastL = new JLabel("Last Name: ");
      last = new JTextField(20);

      JLabel unL = new JLabel("UserName: ");
      username = new JTextField(20);

      JLabel passEnterlab = new JLabel("Password:");
      passenter = new JPasswordField(20);
      
      JLabel typeL = new JLabel("User Type: ");
      type = new JComboBox();
	
      // User type variables
      driver = "Driver";
      maintenance = "Maintenance Professional";
      chOperator = "Clearinghouse Operator";
      type.addItem(driver);
      type.addItem(maintenance);
      type.addItem(chOperator);
	
      JLabel chLabel = new JLabel("ClearingHouse ID (Clearinghouse Operators): ");
      chField = new JTextField(20);
      
      JLabel emailLabel = new JLabel("Email: ");
      emailField = new JTextField(20);
      
      newuser = new JButton("Submit");
      newuser.addActionListener(this);
      
      JPanel registrar = new JPanel();
      registrar.setLayout(new GridBagLayout());
      GridBagConstraints gbc = new GridBagConstraints();
      
      JLabel title = new JLabel("Register your info below:");
      
      gbc.gridx=0;
      gbc.gridy=0;
      registrar.add(title, gbc);
      
      JPanel fieldPanel = new JPanel();
      fieldPanel.setLayout(new GridBagLayout());
      fieldPanel.setOpaque(false);
      
      fieldPanel.add(firstL, gbc);
      gbc.gridx= 1;
      fieldPanel.add(first,gbc);

      gbc.gridy=1;
      gbc.gridx=0;
      fieldPanel.add(lastL, gbc);
      gbc.gridx=1;
      fieldPanel.add(last, gbc);

      gbc.gridy=2;
      gbc.gridx=0;
      fieldPanel.add(unL, gbc);
      gbc.gridx=1;
      fieldPanel.add(username, gbc);
      
      gbc.gridy=3;
      gbc.gridx=0;
      fieldPanel.add(passEnterlab, gbc);
      gbc.gridx=1;
      fieldPanel.add(passenter, gbc);

      gbc.gridy=4;
      gbc.gridx=0;
      fieldPanel.add(typeL, gbc);
      gbc.gridx=1;
      fieldPanel.add(type, gbc);

      gbc.gridy=5;
      gbc.gridx=0;
      fieldPanel.add(chLabel, gbc);
      gbc.gridx=1;
      fieldPanel.add(chField, gbc);
	
      gbc.gridy=6;
      gbc.gridx=0;
      fieldPanel.add(emailLabel, gbc);
      gbc.gridx=1;
      fieldPanel.add(emailField, gbc);
      
      gbc.gridy=1;
      gbc.gridx=0;
      gbc.ipady= 200;
      registrar.add(fieldPanel, gbc);
      registrar.setBackground(Color.white);
      
      gbc.gridy=2;
      gbc.ipady = 0;
      registrar.add(newuser, gbc);
      
      popUp.setContentPane(registrar);
      popUp.setSize(600, 400);
      popUp.setVisible(true);
		popUp.pack();
      
      popUp.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    }
    else if(evt.getSource() == submitCH){
      chString = chField.getText();
    }
    else if (evt.getSource() == forgot){
    	
    	forgotWindow = new JFrame("Username and Password Recovery");
    	
		JPanel forgotcontent = (JPanel) forgotWindow.getContentPane();
		forgotcontent.setLayout(new GridBagLayout());
		GridBagConstraints fc = new GridBagConstraints();
		
		fc.gridx = 0;
		fc.gridy = 0;
		
		JLabel instruct1 = new JLabel("Forgot your Username or password? It's ok! just type");
		JLabel instruct2 = new JLabel("in your email address and we'll check our database");
		JLabel instruct3 = new JLabel("for your information and send it to you via email.");
		
                send = new JButton("Submit Request");
                send.addActionListener(this);
	    
		JLabel youremail = new JLabel("Your E-mail address: ");
		
		EM = new JTextField(20);
		EM.addActionListener(this);
		EM.setVisible(true);
		
		fc.gridx =1;
		forgotcontent.add(instruct1, fc);
		fc.gridy = 1;
		forgotcontent.add(instruct2, fc);
		fc.gridy = 2;
		forgotcontent.add(instruct3, fc);
		fc.gridy = 3;
		fc.gridx = 0;
		forgotcontent.add(youremail, fc);
		
		fc.gridx = 1;
		forgotcontent.add(EM, fc);
		
		fc.gridy = 4;
		forgotcontent.add(send, fc);
		
	    setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
	    forgotcontent.setBackground(Color.white);
	    forgotcontent.setVisible(true);   
	    forgotWindow.setContentPane(forgotcontent);
	    forgotWindow.pack();
	    
	    forgotWindow.setSize(600, 300);
	    forgotWindow.setVisible(true);
    }
    
    else if(evt.getSource() == send){
    	//Value of EM field to test in database
    	String emailTest = EM.getText();
    	String uName, pass, message="";
    	
    	ResultSet retrieve;
    	try{
    		retrieve = stmt.executeQuery("SELECT * FROM USERS WHERE EMAIL='"+emailTest+"'");
    		
    		//TODO: retrieve password and username from database where EMAIL is found
    		//      then put this information into "message" string for email
    		
                    	
                message = "Your username is : "+ retrieve.getString("UID")+ "\nYour password is : "+ retrieve.getString("PASSWORD");;
    	
    	}
    	catch(SQLException not){
    		System.out.println("Given E-mail not found in database!\n"+not);
        }

    	System.out.println("Sending email to : "+emailTest);
    	//sends email
    	sendEmail(emailTest, "Your AutoBiography Account Information",message);
        System.out.println("Email sent!");

        forgotWindow.setVisible(false);
    	
    }

    else if (evt.getSource() == newuser){
      String firstname, lastname, uname, secret, utype="", emailString;
      int uIndex;
      int num_vehic = 0;
        //Use regular expressions to eliminate non-alphanumeric text from inputs
      firstname = sanitize(first.getText());
       lastname = sanitize(last.getText());
       uname = sanitize(username.getText());
       secret = sanitize(new String(passenter.getPassword()));
       uIndex = type.getSelectedIndex();
       if(uIndex==0){
         utype="Driver";
         chString = "NULL";
       }
       else if(uIndex == 1){
         utype="Maintenance";
         chString ="NULL";
       }
       else if(uIndex == 2){
         utype = "CH Operator";
		   chString = sanitize(chField.getText());
       }  
       emailString = emailField.getText();
      
      boolean valid = true;
      // Check that all fields were filled out appropriately
      if (firstname.equals("") || lastname.equals("") || uname.equals("") || secret.equals("") || utype.equals("")){
        JOptionPane.showMessageDialog(this, "You must enter an alphanumeric value for all fields.");
        valid = false;
      }
      else if(firstname.equals("First Name") || lastname.equals("Last Name") || uname.equals("User ID") || utype.equals("User Type")){
        JOptionPane.showMessageDialog(this, "You must enter a non-default alphanumeric value for all fields.");
        valid = false;
      }
      ResultSet rstest = null;
        //Acquire Resultset to test primary key uniqueness
      try{
        PreparedStatement pstmttest = connect.prepareStatement("SELECT * FROM USERS WHERE UID = ?");
          //choice = 4
        pstmttest.setString(1, uname);
        rstest = pstmttest.executeQuery();
      }
      catch(Exception d){
        JOptionPane.showMessageDialog(this, "Can't test if the username is unique:\n\n" + d.toString());
        valid = false;
      }
        
        //Try to load user values with that name. If the result set exists, require a different name.
      try{
        boolean found = true;
        if (valid){
          found = rstest.next();
        }
        if(valid && found){
          JOptionPane.showMessageDialog(this, "That Username is not unique.");
          valid = false;
        }
      }
      catch(Exception i){
        JOptionPane.showMessageDialog(this, "Can't test if the username is unique:\n\n" + i.toString());
        valid = false;
      }
       if(valid){
         SecureLogin safe = new SecureLogin();
           
           //Try to add the user, otherwise, back to login screen.
           
         try{
           safe.createUser(connect, uname, secret, firstname, lastname, utype, num_vehic, chString, emailString);
           JOptionPane.showMessageDialog(this, "You have been successfully added.");

           String message ="Welcome to AutoBiography! \n\nYour username is: "+uname+"\nYour password is: "+secret;
           sendEmail(emailString,"Welcome to AutoBiography!",message);
           
         }
         catch(Exception sqle){
           System.out.println("ERROR REGISTERING NEW USER\n\n" + sqle);
         }
         finally{
           popUp.setVisible(false);
         }
       }//end if valid
    }
    
  }
  
private User returnUser(ResultSet rset){
    User currUser = null;
    try{
        rset.next();
        currUser = new User(rset.getString("FIRSTNAME"), rset.getString("LASTNAME"), rset.getString("UID"), rset.getString("PASSWORD"), rset.getString("USERTYPE"), rset.getString("EMAIL"),rset.getInt("NUMVEHICLES"), rset.getString("CH_ID"));
    }
    catch(SQLException sqlf){
        JOptionPane.showMessageDialog(null, "Getting the user from database failed. Returning null user");
        System.out.println(sqlf);
        currUser = new User("NULL", "NULL","NULL","NULL","NULL", "NULL", -1, "NULL");
    }
    finally{
        return currUser;
    }
}
public static String sanitize(String in){
    String result;
    result = in.replaceAll("[^A-Za-z0-9 ]", "");    
    return result;
}

//private static Properties fMailServerConfig = new Properties();





  public static void sendEmail(String aToEmailAddr, String aSubject, String aBody ){
    
    
    
    // Recipient's email ID needs to be mentioned.
    
    //String to = "emm82@pitt.edu";
    
    String to = aToEmailAddr;
    
    // Sender's email ID needs to be mentioned
    
    String from = "evan.m.mccullough@gmail.com";
    
    
    
    // Assuming you are sending email from localhost
    
    String host = "smtp.gmail.com";
    
    
    
    // Get system properties
    
    Properties props = System.getProperties();
    
    props.put("mail.transport.protocol", "smtp");
    
    props.setProperty("mail.smtp.host", host);
    
    props.setProperty("mail.smtp.user", from);
    
    props.setProperty("mail.smtp.password", "BIGred053");
    
    props.setProperty("mail.smtp.port", "587"); // 587 is the port number of yahoo mail
    
    props.setProperty("mail.smtp.auth", "true");
    
    props.put("mail.smtp.starttls.enable","true");
    
    
    
    // Get the default Session object.
    
    Session session = Session.getDefaultInstance(props, new MyAuthenticator());
    
    
    
    try{
      
      // Create a default MimeMessage object.
      
      MimeMessage message = new MimeMessage(session);
      
      
      
      // Set From: header field of the header.
      
      message.setFrom(new InternetAddress(from));
      
      
      
      // Set To: header field of the header.
      
      message.addRecipient(Message.RecipientType.TO,
                           
                           new InternetAddress(to));
      
      
      
      // Set Subject: header field
      
      message.setSubject(aSubject);
      
      
      
      // Now set the actual message
      
      message.setText(aBody);
      
      
      
      System.out.println("About to send message.");
      
      // Send message
      
      URLName urln = new URLName("smtp", host, 587, "", "coe-1186-project-team" , "COE1186");
      
      
      
      com.sun.mail.smtp.SMTPSSLTransport trans = new com.sun.mail.smtp.SMTPSSLTransport(session, urln);
      
      
      
      trans.setStartTLS(true);
      
      //trans.send(message);
      
      trans.close();
      
      System.out.println("Sent message successfully....");
      
    }catch (MessagingException mex) {
      
      mex.printStackTrace();
      
    }
    
  }
}